﻿using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using Quartz;
using SqlSugar;

namespace DongFangGuoKai.WMSPlatform.WebApi.Job.JobDetails
{
    [DisallowConcurrentExecution]
    public class EmptyContanierToScrennAreaJob : IJob
    {
        public static List<Exception> _exception = new List<Exception>();
        public readonly ISqlSugarClient _cliet;

        public EmptyContanierToScrennAreaJob(ILogger<EmptyContanierToScrennAreaJob> logger, IAGVService aGVApiService, ISqlSugarClient cliet)
        {

            Logger = logger;
            AGVApiService = aGVApiService;
            _cliet = cliet;
        }
        public ILogger<EmptyContanierToScrennAreaJob> Logger { get; }
        public IAGVService AGVApiService { get; }


        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                var emptyCellList = _cliet.Queryable<t_Cell>().Where(t => t.Status == 1 && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && t.LogicalPartCode == "DistributionArea")
              .OrderBy(o => o.LineNO)
              .OrderBy(o => o.LayerNO)
              .OrderBy(o => o.ColumnNO)
              .Take(5).ToList();

                Logger.LogWarning("0 */1  5-16 ? * MON-FR");
                if (emptyCellList != null && emptyCellList.Count > 0)
                {
                    foreach (var emptyToCell in emptyCellList)
                    {
                        var pallet = _cliet.Queryable<t_Pallet>().First(t => t.PalletBarcode == emptyToCell.LogicalPartCode);
                        if (pallet != null)
                        {
                            Logger.LogError($"分拨仓位：{emptyToCell.Name}分配托盘：{pallet.PalletName}");
                            return Task.CompletedTask;
                        }

                        var fromCell = _cliet.Queryable<t_Cell>().Where(t => t.IsLock == false && t.LogicalPartCode != "DistributionArea" && t.BusinessType == 0 && t.FullStatus == 0 && t.Status == 1).First();
                        if (fromCell == null)
                        {
                            Logger.LogError($"空托盘仓位不存在！");
                            return Task.CompletedTask;
                        }
                        var fromCellPallet = _cliet.Queryable<t_Pallet>().First(t => t.LogicalPartCode == fromCell.Code);
                        if (fromCellPallet == null)
                        {
                            Logger.LogError($"仓位找不到空托盘信息！");
                            return Task.CompletedTask;
                        }

                        _cliet.Ado.BeginTran();

                        //修改托盘位置信息
                        fromCellPallet.LogicalPartCode = fromCell.Code;
                        fromCellPallet.ERPLocationName = fromCell.ERPCode;
                        fromCellPallet.WarehouseName = fromCell.WhName;
                        fromCellPallet.WarehouseId = fromCell.WhId;
                        fromCellPallet.WarehouseCode = fromCell.WhCode;
                        _cliet.Updateable(fromCellPallet);

                        //目标储位
                        emptyToCell.Status = 2;//锁定仓位  
                        emptyToCell.BusinessType = Domain.Enums.EmBusinessType.Move; //移位
                        emptyToCell.IsLock = true; //锁定
                        _cliet.Updateable(emptyToCell);

                        //源储位
                        fromCell.Status = 2;
                        fromCell.BusinessType = Domain.Enums.EmBusinessType.Move; //移位
                        fromCell.IsLock = true; //锁定
                        _cliet.Updateable(fromCellPallet);

                        Guid guid = Guid.NewGuid();
                        t_Instruct instruct = new t_Instruct()
                        {
                            BusinessGroupId = guid,
                            CreateUserId = 1,
                            CreateUserName = "admin",
                            Status = 2,
                            Action = EmDeviceAction.Transport,
                            WorkDeviceType = EmWorkDeviceType.AGV,
                            InstructType = EmInstructType.Move,
                            ExpectedToLocation = emptyToCell.Code,//目标地址
                            FromLocation = fromCell.Code,   //源地址
                            InstructIndex = 1,
                            PalletBarcode = fromCellPallet.PalletBarcode,
                            ScanedBarcode = fromCellPallet.PalletBarcode,
                            Priority = 9999,
                            FinishedQTY = 0,
                            LogicalCellAddr = emptyToCell.ERPCode,
                            StartTime = DateTime.Now,
                        };
                        _cliet.Updateable(instruct);

                        string ctnrType = "";
                        string taskType = "A13";
                        if (fromCellPallet.Type == 1)
                        {
                            ctnrType = "2";

                        }
                        else if (fromCellPallet.Type == 2)
                        {
                            ctnrType = "1";

                        }
                        //添加任务单
                        AddTaskModel taskModel = new AddTaskModel();

                        //生成32位uuid
                        taskModel.reqCode = guid.ToString("N");
                        taskModel.clientCode = "PDA";
                        //大料箱任务类型
                        taskModel.TaskTyp = taskType;


                        taskModel.CtnrTyp = ctnrType;
                        //生成36位uuid
                        taskModel.taskCode = guid.ToString();

                        //任务起始点仓位编码
                        taskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        PositionCode=fromCell.ERPCode,// 起始地址 D00080A2502013
                        Type="05"
                    },
                    new PositionCodePathDto() {
                        PositionCode=emptyToCell.ERPCode,//ERP目标地址
                        Type="05"
                    }
                };
                        var res = AGVApiService.CreateTask(taskModel);
                        if (res.code == "1")
                        {
                            _cliet.Ado.RollbackTran();
                            Logger.LogError("AGV调用失败：" + res.message);
                            return Task.CompletedTask;
                        }
                        Logger.LogInformation(res.ToJson());
                        _cliet.Ado.CommitTran();


                    }
                }
                Console.WriteLine(DateTime.Now);
                Console.WriteLine("--------------------------");

                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                //JobExecutionException exception = new JobExecutionException(ex);
                //exception.Source = context.JobDetail.JobType.FullName;
                //exception.UnscheduleFiringTrigger = true;
                //_exception.Add(ex);

                //if (_exception.Count >= 3)
                //{
                //    Logger.LogError("Job已暂停");

                //    //停止Job执行
                //    context.Scheduler.PauseJob(context.JobDetail.Key);


                //}
                //throw ex;
                return Task.CompletedTask;
            }

        }
    }
}
